package com.egame.ewidget.provider;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.egame.ewidget.R;
import com.egame.ewidget.model.ContentType;
import com.egame.ewidget.service.WidgetUiService;
import com.egame.ewidget.utility.BrightnessUtility;
import com.egame.ewidget.utility.FlashTorchUtility;
import com.egame.ewidget.utility.LedFlashUtility;
import com.egame.ewidget.utility.MobileDataUtility;
import com.egame.ewidget.utility.RingerModeUtitliy;
import com.egame.ewidget.utility.WiFiUtility;
import com.egame.ewidget.utils.Utils;

public class SwitchReceiver extends BroadcastReceiver {

	private static final String TAG = SwitchReceiver.class.getSimpleName();

	public static final int NOTIFICATION_ID = 7890;
	public static final int REQUEST_CODE = 123321;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		// Log.d("Kai", intent.getAction());

		if (context == null || intent == null)
			return;

		if (Utils.isIntentOkay(intent)) {

			NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
					context);
			mBuilder.setSmallIcon(R.drawable.ic_launcher);
			mBuilder.setOngoing(true);
			mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);

			RemoteViews view = new RemoteViews(context.getPackageName(),
					R.layout.appwidget_utils);

			String action = intent.getAction();

			int unknown = ContentType.UNKNOWN.getContentId();

			if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {

				int wifiState = intent.getIntExtra(
						WifiManager.EXTRA_WIFI_STATE,
						WifiManager.WIFI_STATE_UNKNOWN);
				// String wifiStateText = "No State";

				switch (wifiState) {
				case WifiManager.WIFI_STATE_DISABLING:
					// wifiStateText = "WIFI_STATE_DISABLING";
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_off);
					break;
				case WifiManager.WIFI_STATE_DISABLED:
					// wifiStateText = "WIFI_STATE_DISABLED";
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_off);
					break;
				case WifiManager.WIFI_STATE_ENABLING:
					// wifiStateText = "WIFI_STATE_ENABLING";
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_on);
					break;
				case WifiManager.WIFI_STATE_ENABLED:
					// wifiStateText = "WIFI_STATE_ENABLED";
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_on);
					break;
				case WifiManager.WIFI_STATE_UNKNOWN:
					// wifiStateText = "WIFI_STATE_UNKNOWN";
					break;
				default:
					break;
				}
				// Log.d("Kai", "onReceive Broadcast > WiFiState: "
				// + wifiStateText);

				// if (WiFiUtility.isEnabled(context)) {
				// view.setImageViewResource(R.id.iv_wifi_utils,
				// R.drawable.ic_widget_wifi_on);
				//
				// } else {
				// view.setImageViewResource(R.id.iv_wifi_utils,
				// R.drawable.ic_widget_wifi_off);
				//
				// }

				// if (MobileDataUtility.isEnabled(context)) {
				// view.setImageViewResource(R.id.iv_data_connection_utils,
				// R.drawable.ic_widget_mobile_data_on);
				//
				// } else {
				// view.setImageViewResource(R.id.iv_data_connection_utils,
				// R.drawable.ic_widget_mobile_data_off);
				//
				// }

			} else if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)
					|| "android.intent.action.ANY_DATA_STATE".equals(action)) {
				ConnectivityManager conMan = (ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE);

				// mobile
				State mobile = conMan.getNetworkInfo(0).getState();

				// //wifi
				// State wifi = conMan.getNetworkInfo(1).getState();

				if (mobile == NetworkInfo.State.CONNECTED
						|| mobile == NetworkInfo.State.CONNECTING) {
					// mobile
					view.setImageViewResource(R.id.iv_data_connection_utils,
							R.drawable.ic_widget_mobile_data_on);

				} else if (mobile == NetworkInfo.State.DISCONNECTED
						|| mobile == NetworkInfo.State.DISCONNECTING) {
					view.setImageViewResource(R.id.iv_data_connection_utils,
							R.drawable.ic_widget_mobile_data_off);
				}
				// else if (wifi == NetworkInfo.State.CONNECTED || wifi ==
				// NetworkInfo.State.CONNECTING)
				// {
				// //wifi
				// }
				//
			} else if (WidgetUiService.ACTION_UTIL_WIDGET_WIFI_CLICKED

			.equals(action)) {
				if (WiFiUtility.isEnabled(context)) {
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_off);
					WiFiUtility.setEnabled(context, false);
				} else {
					view.setImageViewResource(R.id.iv_wifi_utils,
							R.drawable.ic_widget_wifi_on);
					WiFiUtility.setEnabled(context, true);
				}
			} else if (WidgetUiService.ACTION_UTIL_WIDGET_DATA_CONNECTION_CLICKED

			.equals(action)) {

				if (MobileDataUtility.isEnabled(context)) {
					view.setImageViewResource(R.id.iv_data_connection_utils,
							R.drawable.ic_widget_mobile_data_off);
					MobileDataUtility.setMobileDataEnabled(context, false);

				} else {
					view.setImageViewResource(R.id.iv_data_connection_utils,
							R.drawable.ic_widget_mobile_data_on);
					MobileDataUtility.setMobileDataEnabled(context, true);

				}
			} else if (WidgetUiService.ACTION_UTIL_WIDGET_FLASH_TORCH_CLICKED
					.equals(action)) {

				if (!FlashTorchUtility.isFlashLightAccessible(context)) {
					closeStatusBar(context);
					Toast.makeText(context, "Flash not suport",
							Toast.LENGTH_LONG).show();
					return;
				}

				int state = intent.getIntExtra(
						FlashTorchUtility.EXTRA_CHANGE_FLASH_TORCH, unknown);
				if (state == unknown) {
					state = FlashTorchUtility.isFlashLightEnabled(context) ? FlashTorchUtility.FLASH_TORCH_ENABLED
							: FlashTorchUtility.FLASH_TORCH_DISABLED;
				}

				boolean enableFlashTorch = (state == FlashTorchUtility.FLASH_TORCH_ENABLED) ? false
						: true;

				boolean outcome = FlashTorchUtility.setFlashLightEnabled(
						context, enableFlashTorch);

				if (outcome) {
					if (enableFlashTorch) {
						view.setImageViewResource(R.id.iv_flash_utils,
								R.drawable.flash_on);
					} else {
						view.setImageViewResource(R.id.iv_flash_utils,
								R.drawable.flash_off);
					}

				} else {
					closeStatusBar(context);
					Toast.makeText(context, "Camera already in use",
							Toast.LENGTH_LONG).show();
				}

			} else if (WidgetUiService.ACTION_UTIL_WIDGET_BRIGHTNESS_CLICKED
					.equals(action)) {
				int contentState = BrightnessUtility.getBrightnessMode(context);

				contentState = BrightnessUtility.nextMode(contentState);
				if (contentState == BrightnessUtility.BRIGHTNESS_AUTO) {

					view.setImageViewResource(R.id.iv_brightness_utils,
							R.drawable.ic_brightness_auto);

				} else if (contentState == BrightnessUtility.BRIGHTNESS_LOW) {
					view.setImageViewResource(R.id.iv_brightness_utils,
							R.drawable.ic_brightness_low);

				} else if (contentState == BrightnessUtility.BRIGHTNESS_MEDIUM) {
					view.setImageViewResource(R.id.iv_brightness_utils,
							R.drawable.ic_brightness_medium);

				} else if (contentState == BrightnessUtility.BRIGHTNESS_HIGH) {
					view.setImageViewResource(R.id.iv_brightness_utils,
							R.drawable.ic_brightness_hight);

				}

				BrightnessUtility.setBrightnessMode(context, contentState);
			} else if (WidgetUiService.ACTION_UTIL_WIDGET_RINGER_MODE_CLICKED
					.equals(action)) {
				int currentState = RingerModeUtitliy.getRingerMode(context);

				// Log.d("Kai", "click " + contentState);
				int contentState = RingerModeUtitliy.nextMode(currentState);

				if (contentState == RingerModeUtitliy.RING_MODE_NORMAL) {
					view.setImageViewResource(R.id.iv_ring_mode_utils,
							R.drawable.ic_ringer_nomal);

				} else if (contentState == RingerModeUtitliy.RING_MODE_SILENT) {
					view.setImageViewResource(R.id.iv_ring_mode_utils,
							R.drawable.ic_ringer_silent);

				} else if (contentState == RingerModeUtitliy.RING_MODE_VIBRATE) {
					view.setImageViewResource(R.id.iv_ring_mode_utils,
							R.drawable.ic_ringer_vibarete);

				}

				RingerModeUtitliy.setRingerMode(context, contentState);
			}

			mBuilder.setContent(view);

			Notification notification = mBuilder.build();
			notification.when = 100;

			NotificationManager mNotificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			mNotificationManager.notify(NOTIFICATION_ID, notification);
		}
	}

	public void closeStatusBar(Context context) {
		Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		context.sendBroadcast(it);
	}

	public static int[] setStaticStatus(Context context) {
		boolean isWiFiEnabled = WiFiUtility.isEnabled(context);
		boolean isMobileDataEnabled = MobileDataUtility.isEnabled(context);
		int brightnessMode = BrightnessUtility.getBrightnessMode(context);
		int ringMode = RingerModeUtitliy.getRingerMode(context);
		boolean isFlashTorchEnabled = LedFlashUtility
				.isFlashLightEnabled(context);
		int[] statusesArray = { -1, -1, -1, -1, -1 };

		statusesArray[ContentType.WIFI.getContentId()] = isWiFiEnabled ? WiFiUtility.WIFI_ENABLED
				: WiFiUtility.WIFI_DISABLED;
		statusesArray[ContentType.MOBILE_DATA.getContentId()] = isMobileDataEnabled ? MobileDataUtility.MOBILE_DATA_ENABLED
				: MobileDataUtility.MOBILE_DATA_DISABLED;
		statusesArray[ContentType.RINGER_MODE.getContentId()] = ringMode;
		statusesArray[ContentType.BRIGHTNESS_MODE.getContentId()] = brightnessMode;
		statusesArray[ContentType.FLASH_TORCH.getContentId()] = isFlashTorchEnabled ? FlashTorchUtility.FLASH_TORCH_ENABLED
				: FlashTorchUtility.FLASH_TORCH_DISABLED;

		return statusesArray;
	}

	public static void updateSwitchGUI(Context context,
			NotificationCompat.Builder notifiBuilder, int[] statusArray) {
		if (context == null || notifiBuilder == null)
			return;

		RemoteViews view = new RemoteViews(context.getPackageName(),
				R.layout.appwidget_utils);
		updateSwitchStatus(context, view, statusArray, REQUEST_CODE);
		notifiBuilder.setContent(view);
	}

	private static void updateSwitchStatus(Context context,
			RemoteViews remoteView, int[] statusesArray, int requestCode) {
		int i = 0;
		for (i = 0; i < statusesArray.length; i++) {
			updateField(context, remoteView, ContentType.getContentType(i),
					statusesArray[i], requestCode);
		}
	}

	private static void updateField(Context context, RemoteViews remoteViews,
			ContentType contentType, int contentState, int requestCode) {
		int viewId = 0, scrId = 0, eventId = 0;
		String action = "";
		Log.d("UtilsWidgetProvider",
				"======================UtilsWidgetProvider>> updateField ==>: "
						+ contentType.name());

		switch (contentType) {
		case WIFI:
			action = WidgetUiService.ACTION_UTIL_WIDGET_WIFI_CLICKED;
			viewId = R.id.iv_wifi_utils;
			eventId = R.id.bt_wifi_utils;

			if (contentState == WiFiUtility.WIFI_ENABLED) {
				scrId = R.drawable.ic_widget_wifi_on;
			} else if (contentState == WiFiUtility.WIFI_DISABLED) {
				scrId = R.drawable.ic_widget_wifi_off;
			} else if (contentState == WiFiUtility.WIFI_ENABLING) {
				scrId = R.drawable.ic_widget_wifi_on;
			} else if (contentState == WiFiUtility.WIFI_DISABLING) {
				scrId = R.drawable.ic_widget_wifi_off;
			}

			break;
		case MOBILE_DATA:
			action = WidgetUiService.ACTION_UTIL_WIDGET_DATA_CONNECTION_CLICKED;
			viewId = R.id.iv_data_connection_utils;
			eventId = R.id.bt_data_connection_utils;

			if (contentState == MobileDataUtility.MOBILE_DATA_ENABLED
					|| contentState == MobileDataUtility.MOBILE_DATA_ENABLING) {
				scrId = R.drawable.ic_widget_mobile_data_on;
			} else if (contentState == MobileDataUtility.MOBILE_DATA_DISABLED
					|| contentState == MobileDataUtility.MOBILE_DATA_DISABLING) {
				scrId = R.drawable.ic_widget_mobile_data_off;
			}

			break;
		case BRIGHTNESS_MODE:
			action = WidgetUiService.ACTION_UTIL_WIDGET_BRIGHTNESS_CLICKED;
			viewId = R.id.iv_brightness_utils;
			eventId = R.id.bt_brightness_utils;

			if (contentState == BrightnessUtility.BRIGHTNESS_AUTO) {
				scrId = R.drawable.ic_brightness_auto;
			} else if (contentState == BrightnessUtility.BRIGHTNESS_LOW) {
				scrId = R.drawable.ic_brightness_low;
			} else if (contentState == BrightnessUtility.BRIGHTNESS_MEDIUM) {
				scrId = R.drawable.ic_brightness_medium;
			} else if (contentState == BrightnessUtility.BRIGHTNESS_HIGH) {
				scrId = R.drawable.ic_brightness_hight;
			}

			break;
		case RINGER_MODE:
			action = WidgetUiService.ACTION_UTIL_WIDGET_RINGER_MODE_CLICKED;
			viewId = R.id.iv_ring_mode_utils;
			eventId = R.id.bt_ring_mode_utils;

			if (contentState == RingerModeUtitliy.RING_MODE_NORMAL) {
				scrId = R.drawable.ic_ringer_nomal;
			} else if (contentState == RingerModeUtitliy.RING_MODE_SILENT) {
				scrId = R.drawable.ic_ringer_silent;
			} else if (contentState == RingerModeUtitliy.RING_MODE_VIBRATE) {
				scrId = R.drawable.ic_ringer_vibarete;
			}

			break;
		case FLASH_TORCH:
			action = WidgetUiService.ACTION_UTIL_WIDGET_FLASH_TORCH_CLICKED;
			viewId = R.id.iv_flash_utils;
			eventId = R.id.bt_flash_utils;

			if (FlashTorchUtility.isFlashLightEnabled(context)) {
				scrId = R.drawable.flash_on;
			} else {
				scrId = R.drawable.flash_off;
			}

			if (contentState == FlashTorchUtility.FLASH_TORCH_ENABLED) {
				scrId = R.drawable.flash_on;

			} else if (contentState == FlashTorchUtility.FLASH_TORCH_DISABLED) {
				scrId = R.drawable.flash_off;
			}

			break;
		default:

		}

		if (scrId != 0)
			remoteViews.setImageViewResource(viewId, scrId);

		// if (action.length() > 0) {
		// Intent serviceIntent = new Intent(action);
		// PendingIntent pendingIntent = PendingIntent.getService(context,
		// requestCode, serviceIntent, 0);
		// remoteViews.setOnClickPendingIntent(eventId, pendingIntent);
		// }

		Intent switchIntent = new Intent(context, SwitchReceiver.class);
		switchIntent.setAction(action);
		PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(context,
				0, switchIntent, 0);

		remoteViews.setOnClickPendingIntent(viewId, pendingSwitchIntent);
	}

}
